import json
import os
import re
import time

import xlrd
from .addToHtml import addData, finishAdd
from .process import process_analysis
from .toExcel import toExcel

# rootpath = "D:/pythoncc/saved files"
allpath = []
allname = []
num = 0
words = '项目支出绩效目标'
ano_words = '绩效目标表'
no_use_wd1 = '北京市人民政府研究室2021年项目支出绩效目标申报表目录'
no_use_wd2 = '0.绩效目标目录'
ID = "项目名称"
T_ID = "总\n体\n目\n标"
Sum_M = "年度资金总额"
Get_M = "其中：财政拨款（万元，6位小数）"
Other_M = "其他资金（万元，6位小数）"
key_list = ['信息化', '软件', '硬件', '服务器', '云', '咨询', '数据库', '安防', '舆情', '大数据', '物联网', '通信', '光纤', '线路', 'AI', 'ICT']
dataList = {'list': []}
excelData = []


def excel(root_path):
    def getallfile(path):
        allfilelist = os.listdir(path)
        for file in allfilelist:
            filepath = os.path.join(path, file)
            # file_name = file.encode("utf-8").decode("utf-8")
            # search_obj = re.search(words, file_name)
            if os.path.isdir(filepath):
                file_name = file.encode("utf-8").decode("utf-8")
                search_obj = re.search(words, file_name)
                search_obj1 = re.search(ano_words, file_name)
                if search_obj:
                    pass
                    # print(file)
                    # print(search_obj.group())
                elif search_obj1:
                    pass
                    # print(file)
                else:
                    getallfile(filepath)
            elif os.path.isfile(filepath):
                os.remove(filepath)
                continue

    def delete_gap_dir(dir):
        if os.path.isdir(dir):
            for d in os.listdir(dir):
                delete_gap_dir(os.path.join(dir, d))
            if not os.listdir(dir):
                os.rmdir(dir)
                # print('移除空目录：' + dir)

    def format(_list):
        buffer = []
        for item in _list:
            if item.value is not '':
                buffer.append(item.value)
        return buffer

    def dict(path):
        workbook = xlrd.open_workbook(path)
        sheet = workbook.sheet_by_index(0)
        data = {'id': '', 'name': '', 'type': '', 'department': '', 'company': '', 'property': '', 'ddl': '',
                'person': '', 'tel': '', 'money': '', 'target': '', 'isInfo': ''}
        global num
        flag = 0
        num = num + 1
        data['id'] = num
        for i in range(1, sheet.nrows):
            temp = sheet.cell_value(i, 0)
            match_obi = re.match(ID, temp)
            if match_obi:
                n = i
        # 这行是项目名称和项目类型名称在第1个，类型在第3个，如果没有类型，就输出无类型
        res = format(sheet.row(n))
        length = len(res)
        if length == 4:
            # print(res[1], res[3])
            data['name'] = res[1]
            data['type'] = res[3]
        else:
            # print(res[1], "无类型")
            data['name'] = res[1]
            data['type'] = "无类型"

        # 这行是一级主管部门和项目申报单位，这行没有出现缺失数据的情况，同样是第一个和第三个
        res1 = format(sheet.row(n + 1))
        # print(res1[1], res1[3])
        data['department'] = res1[1]
        data['company'] = res1[3]

        # 这行是项目属性和项目期，同样有两个未规定项目期
        res2 = format(sheet.row(n + 2))
        length1 = len(res2)
        if length1 == 4:
            data['property'] = res2[1]
            data['ddl'] = res2[3]
            # print(res2[1], res2[3])
        else:
            data['property'] = res2[1]
            data['ddl'] = "无"
            # print(res2[1], "无项目期")

        # 这行是责任人和联系电话,分三个情况
        res3 = format(sheet.row(n + 3))
        length2 = len(res3)
        if length2 == 2:
            data['person'] = "无"
            data['tel'] = "无"
            # print("无责任人", "无联系电话")
        elif length2 == 3:
            tem = "联系电话"
            if re.search(tem, res3[1]):
                data['person'] = "无"
                data['tel'] = res3[2]
                # print("无责任人", res3[2])
            else:
                data['person'] = res3[1]
                data['tel'] = "无"
                # print(res3[1], "无联系电话")
        else:
            data['person'] = res3[1]
            data['tel'] = res3[3]
            # print(res3[1], res3[3])

        # 这行是年度资金总额
        d = 0
        for t in range(1, sheet.nrows):
            m_match = re.search(Sum_M, sheet.cell_value(t, 0))
            if m_match:
                d = t
        try:
            g_search = re.search(Get_M, sheet.cell_value(d + 1, 0))
            o_search = re.search(Other_M, sheet.cell_value(d + 2, 0))
            g_res = format(sheet.row(d + 1))
            o_res = format(sheet.row(d + 2))
            g_len = len(g_res)
            o_len = len(o_res)
            if g_search:
                if o_search:
                    if g_len == 2 and o_len == 2:
                        n1 = g_res[g_len - 1]
                        n2 = o_res[o_len - 1]
                        if type(n1) == str:
                            n1 = n1.replace(',', '')
                            n1 = re.match(r'^\d+(\.\d+)?', n1).group()
                        if type(n2) == str:
                            n2 = n2.replace(',', '')
                            n2 = re.match(r'^\d+(\.\d+)?', n2).group()
                        # print(n1, n2)
                        # if n1 == '70000000':
                        #     print(data)
                        #     print(n1, n2)
                        data['money'] = float(n1) + float(n2)
                        # data['money'] = float(g_res[g_len - 1]) + float(o_res[o_len - 1])
                    elif g_len == 1:
                        data['money'] = o_res[o_len - 1]
                    else:
                        data['money'] = g_res[g_len - 1]
                else:
                    data['money'] = g_res[g_len - 1]
            else:
                data['money'] = o_res[o_len - 1]
        except:
            data['money'] = g_res[1]
        # 这行是总体目标
        global m
        for j in range(1, sheet.nrows):
            _temp = sheet.cell_value(j, 0)
            match_obj = re.search(T_ID, _temp)
            if match_obj:
                m = j
        res5 = format(sheet.row(m))
        data['target'] = res5[1]
        # print(res5[1])
        for list in key_list:
            key = re.search(list, res[1])
            _key = re.search(list, res5[1])
            if key or _key:
                flag = flag + 1
        if flag > 1:
            data['isInfo'] = "是"
            # print(res[1], "信息化")
        else:
            data['isInfo'] = "否"
            # print(res[1], "不是信息化")

        # return data
        # addData(data)
        global dataList
        global excelData
        if data['isInfo'] == "是":
            dataList['list'].append(data)
        excelData.append(data)

    def get_excel(path):
        files = os.listdir(path)
        for file in files:
            filepath = os.path.join(path, file)
            # file_name = file.encode("utf-8").decode("utf-8")
            # sch_obj = re.search(no_use_wd, file_name)
            if os.path.isdir(filepath):
                get_excel(filepath)
            # elif sch_obj:
            # print(file)
            # os.remove(filepath)
            else:
                if file.endswith(".xlsx"):
                    if re.match('^0?[-.]?[ ]?目录', file):
                        # print(file)
                        os.remove(filepath)
                    # print(file)
                    # dict(filepath)
                elif file.endswith(".xls"):
                    if re.match('^0?[-.]?[ ]?目录', file):
                        # print(file)
                        os.remove(filepath)
                    elif re.match(no_use_wd1, file) or re.match(no_use_wd2, file):
                        # print(file)
                        os.remove(filepath)
                    # print(file)
                    # dict(filepath)
                else:
                    os.remove(filepath)

    def read_excel(path):
        _files = os.listdir(path)
        for _file in _files:
            _filepath = os.path.join(path, _file)
            if os.path.isdir(_filepath):
                read_excel(_filepath)
            else:
                process_analysis(_filepath)
                dict(_filepath)

    t1 = time.clock()
    getallfile(root_path)  # 筛选出要的文件
    delete_gap_dir(root_path)  # 筛掉空文件
    get_excel(root_path)  # 删除不需要的表
    read_excel(root_path)  # 读表
    t2 = time.clock()
    print(f'analysis cost time: {t2 - t1}s')
    with open("./result/result.json", "w") as fp:
        global dataList
        fp.write(json.dumps(dataList, indent=4))
    global excelData
    toExcel(excelData)
    # finishAdd()
